package net.dgg.zz.common.controller;

import com.alibaba.fastjson.JSONObject;
import net.dgg.common.tools.exception.ExceptionUtils;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserDTO;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DataTableResponse;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 公用Controller
 */
@Controller
@RequestMapping("/zzsc/common")
public class CommonController extends DggBaseController {

    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Resource
    private DesUtil desUtil;
    @Value("${product_center_url}")
    private String productCenterUrl;
    @Value("${threeBusinessApi}")
    private String threeBusinessApi;

    /**
     * 查询所有事业部
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "/find_all_syb")
    @ResponseBody
    public DggRestResponse findAllSyb() {
        Map map = new HashMap();
        map.put("level", "ORG_LEVEL_1");
        map.put("orgId", "1 ");
        map.put("busType","BUS_YT_ZZ");
        List<Map> orgs = cmsService.findOrgs(map,1);
        return this.getSuccessResponse(orgs);
    }

    /**
     * 查询字典
     *
     * @return
     */
    @NLog()
    @ResponseBody
    @RequestMapping("/tree_book_list")
    public DggRestResponse treeBookList(@RequestParam String code, @RequestParam int type, @RequestParam int level) {
        try {
            return this.getSuccessResponse(zzCommonMangerExtService.queryTreeBookListByCode(code, type, level));
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 查询字典接口
     *
     * @param code   编码
     * @param status 状态 1：启用，0：禁用，无：所有
     * @param type   1：根据分类编码查询下级第一级分类（用于Select选择）
     *               2：根据分类编码查询所有下级分类（用于Tree选择无父级的）
     *               3：根据分类编码查询所有下级分类包含自己（用于Tree选择有父级的）
     * @param level  查询深度，如（1，2，3）表示查询到下面第几级
     * @return 字典集合
     */
    @NLog()
    @RequestMapping(value = "/get_tree_book_list")
    @ResponseBody
    public List<Map> getTreeBookList(String code, Integer status, Integer type, Integer level) {
        List<Map> treeBooks = cmsService.getTreeBookList(code, status, type, level);
        return treeBooks;
    }

    /**
     * 选择人员demo /zzsc/common/user_choose_demo
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "/user_choose_demo")
    public String userChooseDemo() {
        return "/zzsc/annex/userChoose";
    }

    /**
     * 用户选择信息查询
     *
     * @param params ｛
     *               type: 用户信息选择类型
     *               all:全部用户，division：当前登录人所在事业部，department:当前登录人所在部门及以下，role: 查询指定角色用户，
     *               roleCode : 角色Code，
     *               locked: 用户状态，
     *               0、正常；1、锁定；2、离职
     *               ｝
     * @return
     */
    @NLog()
    @RequestMapping(value = "/find_user_choose")
    @ResponseBody
    public DggRestResponse findUserChoose(@RequestParam Map params) {
        List<UserDTO> userDTOList = commonService.findUserDTOList(params);
        return this.getSuccessResponse(userDTOList);
    }

    /**
     * 选择人员弹框页面
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "/user_choose_page")
    public String userChoosePage(@RequestParam Map params, Model model) {
        model.addAttribute("map", params);
        return "/zzsc/annex/userChooseAjax";
    }

    /**
     * 选择人员弹框页面数据
     *
     * @return
     */
    @NLog()
    @ResponseBody
    @RequestMapping(value = "/user_choose_data")
    public DataTableResponse userChooseData(@RequestParam Map params) {
        List<UserDTO> userDTOList = commonService.findUserDTOList(params);
        return new DataTableResponse().data(params, userDTOList);
    }

    /*
     * @Author zsx
     * @Date 2018-08-27 10:08:51
     * @Description  获取当前登录用户事业部id
     * @return DggRestResponse
     */
    @RequestMapping("/get_current_division")
    @ResponseBody
    @NLog
    public DggRestResponse getCurrentDivision() {
        try {
            Long signOrgId = commonService.findUserSyb(sessionManager.getCurrentUser());
            return this.getSuccessResponse(signOrgId);
        } catch (Exception e) {
            return this.getFailResponse("服务器错误,请联系管理员");
        }
    }


    @ResponseBody
    @RequestMapping("/orgs_tree_List")
    public DggRestResponse orgstreeList(@RequestParam Map params) {
        try {
            return this.getSuccessResponse(zzCommonMangerExtService.findOrgs(params));
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 部门选择demo
     *
     * @return
     */
    @NLog()
    @RequestMapping(value = "/organ_tree")
    public String organTree() {
        return "/zzsc/annex/organ_tree";
    }

    /**
     * 部门数据查询
     *
     * @param params ｛
     *               type: 部门查询类型
     *               all:全部部门，division：当前登录人所在事业部下所有部门，department:当前登录人所在部门下所有部门
     *               ｝
     * @return
     */
    @NLog
    @ResponseBody
    @RequestMapping("/organ_tree_data")
    public List<Map<String, Object>> organTreeData(@RequestParam Map params) {
        List<Map<String, Object>> treeList = commonService.findParamsOrgan(params);
        return treeList;
    }


    /*
     * @Author zsx
     * @Date 2018-09-03 11:09:23
     * @Description 查询资质审核拥有权限的人
     * @param roleCode
     */
    @RequestMapping(value = "/find_org_user")
    @ResponseBody
    @NLog()
    public DggRestResponse findOrgUserByRole() {
        List<UserDTO> users = null;
        try {
//            users = commonService.findUserByOrgAndRole();
            users = zzInProcessService.findUserListByQulificationAuditor();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        }
        return this.getSuccessResponse(users);
    }

    /**
     * 翻译指定编码
     *
     * @param codes
     * @return
     */
    @RequestMapping(value = "/translate_code")
    @ResponseBody
    @NLog()
    public DggRestResponse translateCode(@RequestParam String codes) {
        try {
            List<Map> map = commonService.getTreeBookObjMulti(codes);
            return this.getSuccessResponse(map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping("/see_number")
    @NLog()
    public DggRestResponse seeNumber(@RequestParam String number, @RequestParam String type, @RequestParam String getType) {
        try {
            SystemRecord record = new SystemRecord();
            String customer_number = null;
            if (type.equals("1")) {
                record.setOperateType("55");
                record.setRemarks("查看身份证：" + number);
            } else {
                record.setOperateType("56");
                if (getType.equals("2")) {
                    //从接口获取
                    customer_number = zzInProcessService.findPhoneByCustomerId(Long.parseLong(number));
                } else {
                    //生产订单
                    ProductOrder productOrder = zzInProcessService.getScProductOrderById(Long.parseLong(number));
                    customer_number = desUtil.decrypt(productOrder.getCustomerPhone());
                }

                record.setRemarks("查看电话号码：" + customer_number);
            }
            record.setWorkTableName("");
            record.setSource("");
            systemRecordService.save(record);
            return this.getSuccessResponse(customer_number);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 根据组织机构id查询事业部
     *
     * @param orgId
     * @return
     */
    @NLog()
    @ResponseBody
    @RequestMapping("find_org_by_id")
    public DggRestResponse fingOrgById(Long orgId) {
        Map org = cmsService.findOrg(orgId);
        if (StringUtils.isEmpty(org)) {
            return this.getFailResponse("组织机构不存在");

        }
        return this.getSuccessResponse(org);

    }

    /**
     * 获取产品
     *
     * @param proType 二级业态CODE
     */
    @NLog()
    @ResponseBody
    @RequestMapping(value = "/getThreeBusiness.do")
    public DggRestResponse getThreeBusiness(@RequestParam String proType) {
        if (StringUtils.isEmpty(proType)) {
            return getFailResponse("请求失败");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("proType", proType);
        params.put("page",1);
        params.put("limit",100);
        try {
            logger.error("获取产品列表URL："+  (this.productCenterUrl + this.threeBusinessApi));
            logger.error("请求参数："+ JSONObject.toJSONString(params));
            String bas = HttpUtility.postRest(this.productCenterUrl + this.threeBusinessApi, params);
            logger.error("返回结果："+ bas);
            ResultObj resultObj = (ResultObj) JsonUtil.json2Obj(bas, ResultObj.class);
            if (0 != resultObj.getCode()) {
                return getFailResponse(resultObj.getMsg());
            }
            if(StringUtils.isEmpty(resultObj.getData())){
                return getFailResponse(resultObj.getMsg());
            }
            JSONObject json = JSONObject.parseObject(resultObj.getData());
            return getSuccessResponse(json.getString("data"));
        } catch (Exception e) {
            ExceptionUtils.error(e, "/zcsc/common/getThreeBusiness.do", proType);
            return getFailResponse("请求失败");
        }

    }

}
